package com.bizmda.bizsip.source.netty.service;

import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.json.JSONObject;
import com.bizmda.bizsip.common.BizException;
import com.bizmda.bizsip.common.BizMessage;
import com.bizmda.bizsip.common.BizMessageInterface;
import com.bizmda.bizsip.converter.Converter;
import com.bizmda.bizsip.source.api.SourceBeanInterface;
import com.bizmda.bizsip.source.api.SourceClientFactory;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @author shizhengye
 */
@Service
public class NettySourceBean implements SourceBeanInterface {
    private final Converter converter = Converter.getSourceConverter("source1");
    private final Map<String, BizMessageInterface> appServiceMap = new HashMap<>();
    private final BizMessageInterface errorAppService = SourceClientFactory.getAppServiceClient(BizMessageInterface.class, "/source1/error");

    public NettySourceBean() throws BizException {
        // 无操作
    }

    @Override
    public Object process(Object data) throws BizException {
        BizMessage<JSONObject> bizMessage;
        byte[] inBytes = (byte[]) data;

        assert this.converter != null;
        JSONObject jsonObject = this.converter.unpack(inBytes);
        String serviceId = (String) jsonObject.get("serviceId");

        if (CharSequenceUtil.isEmpty(serviceId)) {
            bizMessage = this.errorAppService.call(jsonObject);
            return this.converter.pack(bizMessage.getData());
        }
        BizMessageInterface appService = this.appServiceMap.computeIfAbsent(serviceId,
                key -> SourceClientFactory.getAppServiceClient(BizMessageInterface.class, key));
        bizMessage = appService.call(jsonObject);
        return this.converter.pack(bizMessage.getData());
    }
}
